package com.xhc.demo.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import com.xhc.demo.GlobalConfig;

@Service
public class WeChatService {

    private static final String WECHAT_API_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private RestTemplate restTemplate;

    public String getOpenId(String code) {
        code = java.net.URLEncoder.encode(code, java.nio.charset.StandardCharsets.UTF_8);
        String appId = GlobalConfig.APP_ID;
        String appSecret = GlobalConfig.APP_SECRET;

        String url = WECHAT_API_URL + "?appid=" + appId + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, HttpEntity.EMPTY, String.class);
        return response.getBody();
    }
}
